/**
 * 
 */
package io.potato.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author timl
 * @time 2019年3月10日下午7:59:43
 * net.yeyou.biz.util.FileUtil
 */
public class FileUtil {
	
	/**
	 * 返回文件的后缀名
	 * @param fileName 文件名
	 * @return  后缀 如.txt .xls .jpg
	 */
	public static String getExtention(String fileName) {
		return fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
	}

	public static boolean isTxt(String fileName) {
		return fileName.toLowerCase().endsWith(".txt");
	}

	public static boolean isCsv(String fileName) {
		return fileName.toLowerCase().endsWith(".csv");
	}
	
	public static byte[] readBytes(File file) throws IOException {
		FileInputStream in = new FileInputStream(file);
		byte[] ret = FileUtil.readBytes(in);
		in.close();
		return ret;
	}

	public static byte[] readBytes(InputStream inStream) throws IOException {
		int size = 1024;
		byte[] ba = new byte[size];
		int readSoFar = 0;

		while (true) {
			int nRead = inStream.read(ba, readSoFar, size - readSoFar);
			if (nRead == -1) {
				break;
			}
			readSoFar += nRead;
			if (readSoFar == size) {
				int newSize = size * 2;
				byte[] newBa = new byte[newSize];
				System.arraycopy(ba, 0, newBa, 0, size);
				ba = newBa;
				size = newSize;
			}
		}

		byte[] newBa = new byte[readSoFar];
		System.arraycopy(ba, 0, newBa, 0, readSoFar);
		return newBa;
	}
	
}
